#include "Common.h"

void Session::HandleGameObjectUse(RealmPacket& rdata)
{
	ui64 objguid;
	rdata >> objguid;
	MapHandler* m_map = m_player->GetMapHandler();
	if(!m_map)
		return;
	GameObject* gobj = m_map->GetGameObject(objguid);
	if(!gobj)
	{
		Log->Notice("Session", "Got unknown gameobject with guid: %I64u", objguid);
		return;
	}

	ui8 objtype = gobj->GetByte(GAMEOBJECT_BYTES_1, 1);
	switch(objtype)
	{
	case GAMEOBJECT_TYPE_BARBER_CHAIR:
		{
			m_player->TeleportTo(gobj->GetPosition(), gobj->GetOrientation());
			m_player->SetStandState(6);
			RealmPacket barber(SMSG_ENABLE_BARBER_SHOP);
			m_player->GetSession()->SendPacket(&barber);
			break;
		}

	case GAMEOBJECT_TYPE_CHAIR:
		{
			m_player->TeleportTo(gobj->GetPosition(), gobj->GetOrientation());
			m_player->SetStandState(5);
			break;
		}

	case GAMEOBJECT_TYPE_DOOR:
		{
			if(gobj->GetByte(GAMEOBJECT_BYTES_1, 0))
			{
				gobj->SetUI32Value(GAMEOBJECT_FLAGS, gobj->GetUI32Value(GAMEOBJECT_FLAGS) | 1);
				gobj->SetByte(GAMEOBJECT_BYTES_1, 0, 0);
				TimedEvent* te = new TimedEvent(new CallbackP0<GameObject>(&GameObject::CloseObject, gobj), 20000, 1);
				gobj->AddEvent(te);
			}
			else
			{
				gobj->CloseObject();
			}
			break;
		}

	case GAMEOBJECT_TYPE_SPELLCASTER:
		{
			ui32 spellfocus = gobj->GetInfo()->spellfocus;
			GameObjectTeleport* gTeleport = miscmgr->GetGameObjectTeleport(gobj->GetEntry());
			if(gTeleport)
				spellfocus = gTeleport->spellfocus;

			Spell* sp = new Spell(m_player, dbcSpells.LookupEntry(spellfocus), m_player->GetFreeCastNumber());
			sp->SetUnitTarget(m_player->GetGUID());
			if(gTeleport)
			{
				if(m_player->m_currentspell)
				{
					m_player->SendSpellError(104, spellfocus);
					return;
				}
				sp->SetSourceGameObject(gobj);
				sp->SetCastTime(gTeleport->casttime);
			}
			sp->Start();
			break;
		}
	default:
		Log->Notice("GameObject", "Player %s used GameObject %I64u (type: %u)", m_player->GetName(), objguid, objtype);
		break;
	}
}